package cn.lzj.pet.service.impl;

import cn.lzj.basic.service.impl.BaseServiceImpl;
import cn.lzj.pet.domain.PetType;
import cn.lzj.pet.mapper.PetTypeMapper;
import cn.lzj.pet.service.IPetTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {
    @Autowired
    private  PetTypeMapper petTypeMapper;
    @Override
    public List<PetType> typeTree() {

        HashMap<Long, PetType> map = new HashMap<>();
        List<PetType> allTypes = petTypeMapper.loadAll();
        //for循环遍历
        for (PetType petType : allTypes) {
            //把循环到的类型数据放入map里面
            map.put(petType.getId(),petType);
        }
        List<PetType> typeTree =new ArrayList<>();
        for (PetType petType : allTypes) {
            if(petType.getPid()==null){
                //是顶级类型,添加到类型树里面
                typeTree.add(petType);
            }else{
                Long parent_id = petType.getPid();
                PetType parentType = map.get(parent_id);
                parentType.getChildren().add(petType);
            }
        }
        return typeTree;
    }
}
